package models

import (
	"encoding/json"
	"github.com/beego/beego/v2/client/orm"
	"github.com/beego/beego/v2/core/logs"
	"time"
	"yixiang.co/yshop/models/dto"
)

type YshopStoreProductAttrResult struct {
	Id         int64     `json:"id"`
	ProductId  int64     `json:"productId" valid:"Required;"`
	Result     string    `json:"sliderImage" valid:"Required;"`
	ChangeTime time.Time `orm:"auto_now_add;type(datetime)" json:"change_time"`
}

func init() {
	orm.RegisterModel(new(YshopStoreProductAttrResult))
}

func GetProductAttrResult(productId int64) map[string]interface{} {
	var (
		result YshopStoreProductAttrResult
		data map[string]interface{}
	)
	o := orm.NewOrm()
	o.QueryTable(new(YshopStoreProductAttrResult)).Filter("product_id", productId).One(&result)

	e := json.Unmarshal([]byte(result.Result),&data)
    logs.Error(e)

	return data
}

func AddProductAttrResult(items []dto.FormatDetail, attrs []dto.ProductFormat, productId int64) (id int64, err error) {
	o := orm.NewOrm()
	mapData := map[string]interface{}{
		"attr":  items,
		"value": attrs,
	}
	b, _ := json.Marshal(mapData)
	qs := o.QueryTable(new(YshopStoreProductAttrResult))
	count, _ := qs.Filter("product_id", productId).Count()
	if count > 0 {
		qs.Filter("product_id", productId).Delete()
	}
	var result = YshopStoreProductAttrResult{
		ProductId: productId,
		Result:    string(b),
	}
	id, err = o.Insert(&result)
	logs.Error(err)
	return
}

func DelByProductAttrResult(productId int64) (err error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(YshopStoreProductAttrResult))
	_, err = qs.Filter("product_id", productId).Delete()
	return err
}
